// pages/competition_detail/index.js
import {getMatchDetail,getMatchList} from '../../api/match.js'
import {getScheduleAdd,getScheduleDel} from '../../api/schedule.js'
import { getCoupon } from '../../api/coupon.js'
import { removeObj } from '../../utils/removeObj.js'
import { checkUnPay } from '../../api/order.js'
const app = getApp()
let videoCtx = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPhone:false,
    current: 0, 
    currentTab: 0,
    isRequest: false,
    scheduleId: 0,
    stateIndex: 0,
    openNavList: false,
    navList: [],
    list: [],
    total: 0,
    isRequst: false,
    matchName:'',
    navShowMore: false, // 是否显示下拉按钮
    btnText: {
      "-1": "未开始",
      "0": "去报名",
      "1": "截止报名",
      "2": "已开始"
    },
    shortAddress: '',
    registTime: '2020-04-21 19:16:26',
    deadlineRegist: '2020-04-21 19:16:26',
    timeStart: '2020-04-21 19:16:26',
    videoAutoplay:false,//视频是否自动切换
    interval:'5000',//banner轮播时间
    videoInterval:'5000'//视频剩余播放时间
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(options)
    let matchId = 0
    if (options.id) {
      matchId = options.id
      if (options.images) {
        this.setData({ images: JSON.parse(decodeURIComponent(options.images)) })
      }
      if (options.matchName) {
        this.setData({ matchName: options.matchName })
      }
    } else {
      const scene = decodeURIComponent(options.scene)
      // console.log(scene)
      matchId = scene.split("=")[1].split(":")[0]
      // console.log(matchId)
      let type = scene.split(":")[1].split("=")[1]
      if(type=='2'){
        wx.redirectTo({
          url: '/pages/live_application/index?matchid='+matchId,
        })
      }
    }
    this._getMatchDetail(matchId)
  },
  // 定义视频DOM
  onReady(){
    videoCtx = wx.createVideoContext('myVideo', this)
  },
  
  onShow(){
    this.setData({ isPhone: typeof (app.globalData.modelmeArr) == 'boolean' })
  },
  
  toApplication(){
    let {matchId}=this.data
    wx.navigateTo({
      url: '/pages/live_application/index?matchid=' + matchId,
    })
  },
_checkUnPay(){
  let that = this
  checkUnPay(this.data.matchId).then(res=>{
      if(res.data.flag){
        wx.showModal({
          content: '您有未支付的订单，请先支付或取消，否则无法继续下单',
          success (resx) {
            if (resx.confirm) {
              wx.navigateTo({
                url: '/pages/order-new-detail/index?orderid=' + res.data.order.orderId,
              })
            } else if (resx.cancel) {
            }
          }
        })
      }else{
        that.apply()
      }
  })
},
  //赛事详情
  _getMatchDetail(id) {
    if (!this.data.isRequest) {
      this.setData({isRequest: true})
      getMatchDetail(id).then(res => {
        let arr = res.data;
        if (arr.recommendIds != 0) {
          this._getMatchList(arr.recommendIds)
        }
        const dateNow = new Date(); //获取当前时间
        //时间差的毫秒数
        if (new Date(arr.timeStart.replace(/\-/g, '/')) - dateNow< 0) { //活动开始
          this.setData({ stateIndex: 2 })
        } else if (dateNow - new Date(arr.deadlineRegist.replace(/\-/g, '/')) > 0) { //报名截止
          this.setData({ stateIndex: 1 })
        } else if (dateNow - new Date(arr.registTime.replace(/\-/g, '/')) < 0) { // 还没开始
          this.setData({ stateIndex: -1 })
        }
        arr.date = app.timeFn(arr.timeStart, '-')[4]
        let num = 0
        arr.matchSkuList.forEach(e => {
          if (e.price < num || num == 0) {
            num = e.price
          }
          if (e.qualificateList) {
            e.qualificateList = removeObj(e.qualificateList, ['searchValue', 'createBy', 'createTime', 'updateBy', 'updateTime', 'params'])
          }
        })
        arr.matchSkuList = removeObj(arr.matchSkuList, ['searchValue', 'createBy', 'createTime', 'updateBy', 'updateTime', 'remark', 'sort'])
        arr.navList = removeObj(arr.navList, ['params', 'navId', 'matchId', 'navName', 'searchValue', 'createBy', 'createTime', 'updateBy', 'updateTime', 'remark', 'sort'])
        arr.matchFormList = removeObj(arr.matchFormList, ['formId', 'fieldStr', 'createTime', 'deletedFlag'])
        arr.minPrice = (num + '').split('.')
        // console.time('getTime');
        let title = '￥'+Number(arr.minPrice[0] + (arr.minPrice[1] ? ('.' + arr.minPrice[1]) : '')) + (arr.matchSkuList.length>1?'起':'')
        let width=500;
        let padding = 16;
        let textBottom = 29; // 字体距离底部距离
        let priceFontSize = 26; // 价格字号
        this.setData({...removeObj(arr, ['categoryId', 'categoryName', '__webviewId__', 'time','sysId', 'isOnline', 'createBy', 'createTime', 'deleted', 'countryId', 'provinceId', 'cityId', 'progress', 'updateBy', 'updateTime', 'remark', 'searchValue', 'params']), isRequest: false
        })
        if (arr.navList.length > 0) {
          let allWidth = 0
          wx.createSelectorQuery().selectAll('.tabbox .tabList .tab-title').boundingClientRect(res => {
            res.forEach((e, i) => {
              allWidth += e.width
            })
            this.setData({ navShowMore: allWidth > 686 })
          }).exec()
        }
      })
    }
  },
  addToMatch() {
    if (this.data.isRequest) {
      setTimeout(() => {
        this.addToMatch()
      }, 10)
    } else {
      let {
        matchId,
        matchName,
        shortAddress,
        showTimeStart
      } = this.data
      getScheduleAdd({
        matchId: matchId,
        matchName: matchName,
        timeStart: showTimeStart,
        shortAddress: shortAddress
      }).then(res => {
        if (res.code == 0) {
          wx.showToast({
            title: '添加成功'
          })
          this.setData({
            scheduleId: res.data
          })
        } else {
          wx.showToast({
            title: '添加失败',
            icon: 'none'
          })
        }
      })
    }
  },
  delToMatch() {
    if (this.data.isRequest) {
      setTimeout(() => {
        this.delToMatch()
      }, 10)
    } else {
      wx.showModal({
        title: '提示',
        content: '确定取消添加吗',
        cancelText: '取消',
        cancelColor: '#999999',
        confirmText: '确定',
        confirmColor: '#000000',
        success: res => {
          if (res.confirm) {
            getScheduleDel(this.data.scheduleId).then(res => {
              if (res.code == 0) {
                wx.showToast({
                  title: '已取消',
                  icon: 'none'
                })
                this.setData({ scheduleId: 0 })
              } else {
                wx.showToast({
                  title: '取消失败',
                  icon: 'none'
                })
              }
            })
          }
        }
      })
    }
  },
  openNav() {
    this.setData({
      openNavList: !this.data.openNavList
    })
  },
  //点击查询
  tapRouter(e){
    let { matchId, matchName } = this.data
    if (e.currentTarget.dataset.index==0){
      wx.navigateTo({ url: `/pages/sign_up_search_input/index?title=报名查询&&name=${matchName}&&matchId=${matchId}`})
    }else{
      wx.navigateTo({ url: `/pages/sign_up_search_input/index?title=成绩查询&&name=${matchName}&&matchId=${matchId}`})
    }
  },
  returnFalse() {
    return false;
  },
  
  // 视频出错时执行
  videoErrorCallback(e) {
    this.setData({video:''})
  },

  // 获取赛程列表
  _getMatchList(recommendIds) {
    getMatchList({
      recommendIds: recommendIds
    }, true).then(res => {
      let arr = res.rows;
      let newArr = []
      if (arr.length > 0) {
        arr.forEach(e => {
          newArr.push({ matchId: e.matchId, matchName: e.matchName, images: e.images, image: e.image})
        })
        this.setData({list: newArr})
      }
    })
  },

  //获取更多推荐
  getMoreRecommend() {
  },
  
  // 左下角分享
  share() {
    if (!wx.getStorageSync('userInfo')) {
      wx.showModal({
        title: '您未授权',
        content: '是否前往授权',
        showCancel: true, //是否显示取消按钮
        cancelText: "取消", //默认是“取消”
        cancelColor: '#999999', //取消文字的颜色
        confirmText: "立即前往", //默认是“确定”
        confirmColor: '#666666', //确定文字的颜色
        success: function(res) {
          if (!res.cancel) {
            wx.navigateTo({
              url: '/pages/get_user_info/index',
            })
          }
        }
      })
    } else if (this.data.isRequest) {
      setTimeout(() => {
        this.share()
      }, 10)
    } else {
      wx.navigateTo({
        url: '/pages/share_match/index',
      })
    }
  },

  // 获取swiper下标
  getSwiperIndex(e){
    let {current}=e.detail
    // console.log(current)
    let {video,videoAutoplay}=this.data
    if(video!=''){
      if(current==0){
        if(videoAutoplay){
          videoCtx.play()
        }
      }else{
        videoCtx.pause()
        this.setData({interval:5000})
      }
    }else{

    }
  },

  // 点击暂停
  bindpause(e){
    this.setData({interval:5000})
  },

  bindtimeupdate(e){
    let {duration,currentTime}=e.detail
    // console.log(duration,e.detail)
    let {videoInterval}=this.data
    let interval=Number(duration-currentTime).toFixed(3)*1000
    // console.log(interval)
    if(videoInterval!=interval){
      // console.log(interval)
      setTimeout(()=>{
        this.setData({interval:interval==0?5000:interval})
        if(interval==0){
          this.setData({current:1})
        }
      },1000)
    }
  },

//领取优惠券
  receiveTap(e){
    let { abletake, couponId, hastake, index } = e.currentTarget.dataset
    if (hastake == 0 && abletake==1){//未领且可领时
      getCoupon(couponId).then(res => {
        if (res.code == 0) {
          wx.showModal({
            title: '',
            content: '领取成功',
            showCancel: false,
            confirmColor: "#576B95",
            confirmText: '好的'
          })
          let { couponList}=this.data
          couponList[index].ableTake = 0;
          couponList[index].hasTake=1;
          this.setData({ [`couponList[${index}]`]: couponList[index]})
        } else {
          wx.showToast({
            title: '领取失败',
            icon: 'none'
          })
        }
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(res) {
    let { matchId}=this.data
    　　// 设置菜单中的转发按钮触发转发事件时的转发内容
      var shareObj = {
        path: '/pages/competition_detail/index?id=' + matchId,
        success: function (res) {// 转发成功之后的回调
          if (res.errMsg == 'shareAppMessage:ok') { }
        }
      };
      return shareObj;
  },
  //获取到点击的下标
  getcurrentTab(e) {
    this.setData({
      currentTab: e.currentTarget.dataset.currenttab,
      openNavList: false
    })
  },
  //立即报名 
  apply() {
    let arr = {
      "-1": "赛事未开始报名",
      "1": "赛事截止报名",
      "2": "活动已开始"
    }
    if (this.data.stateIndex == 0) {
      if (!wx.getStorageSync('userInfo')) {
        wx.showModal({
          title: '您未授权',
          content: '是否前往授权',
          showCancel: true, //是否显示取消按钮
          cancelText: "取消", //默认是“取消”
          cancelColor: '#999999', //取消文字的颜色
          confirmText: "立即前往", //默认是“确定”
          confirmColor: '#666666', //确定文字的颜色
          success: function(res) {
            if (!res.cancel) {
              wx.navigateTo({
                url: '/pages/get_user_info/index',
              })
            }
          }
        })
      } else if (this.data.isRequest) {
        setTimeout(()=>{
          this.apply()
        },10)
      } else {
      wx.navigateTo({
        url: "/pages/choose_group/index?time=" + new Date(),
      })
    }
    } else {
      wx.showToast({
        title: arr[this.data.stateIndex],
        icon: 'none'
      })
    }
  }
})